package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.model.SeckillGoods;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.order.model.OrderInfo;
import com.github.benmanes.caffeine.cache.Cache;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;


    /**
     * 返回全部列表
     *
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        return Result.ok(seckillGoodsService.findAll());
    }

    /**
     * 获取实体
     *
     * @param skuId
     * @return
     */
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable("skuId") Long skuId) {
        return Result.ok(seckillGoodsService.getSeckillGoods(skuId));
    }


    //@Autowired
    //private Cache<String, String> seckillCache;
    //String ifPresent = seckillCache.getIfPresent(skuId);


    /**
     * 为当前用户购买意向生成抢购码
     *
     * @param skuId 商品ID
     * @return
     */
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuStr(HttpServletRequest request, @PathVariable("skuId") Long skuId) {
        //1.验证本地缓存中商品状态 必须是 “1”
        String state = (String) CacheHelper.get(skuId.toString());
        if (StringUtils.isBlank(state)) {
            return Result.build(null, ResultCodeEnum.ILLEGAL_REQUEST);
        }
        if ("0".equals(state)) {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
        if ("1".equals(state)) {
            //2.根据SKUID 查询分布式缓存中秒杀商品 获取开始时间，结束时间
            SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
            if (seckillGoods != null) {
                Date startTime = seckillGoods.getStartTime();
                Date endTime = seckillGoods.getEndTime();
                Date now = new Date();
                if (DateUtil.dateCompare(seckillGoods.getStartTime(), now) && DateUtil.dateCompare(now, seckillGoods.getEndTime())) {
                    //3.获取登录用户ID,按照规则生成 或者 将生成的强购码加入缓存Redis
                    String userId = AuthContextHolder.getUserId(request);
                    String encrypt = MD5.encrypt(userId + skuId);
                    //4.返回商品抢购码
                    return Result.ok(encrypt);
                }
            }
        }
        return Result.build(null, ResultCodeEnum.ILLEGAL_REQUEST);
    }


    /**
     * 秒杀请求入队
     *
     * @param request
     * @param skuId    商品ID
     * @param skuIdStr 用户抢购码
     * @return
     */
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillRequestToQueue(HttpServletRequest request, @PathVariable("skuId") Long skuId, String skuIdStr) {
        String userId = AuthContextHolder.getUserId(request);
        return seckillGoodsService.seckillRequestToQueue(userId, skuId, skuIdStr);
    }


    /**
     * 检查秒杀订单-秒杀结果
     *
     * @param skuId
     * @return
     */
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkSeckillResult(HttpServletRequest request, @PathVariable("skuId") Long skuId) {
        //1.获取用户ID
        String userId = AuthContextHolder.getUserId(request);
        //2.调用业务逻辑
        return seckillGoodsService.checkSeckillResult(userId, skuId);
    }


    /**
     * 秒杀订单确认页面渲染需要参数汇总接口
     * @return
     */
    @GetMapping("/auth/trade")
    public Result seckillTradeData(HttpServletRequest request){
        //1.获取当前登录用户ID
        String userId = AuthContextHolder.getUserId(request);

        //2.调用业务逻辑汇总数据
        return seckillGoodsService.seckillTradeData(userId);
    }


    /**
     * 保存秒杀订单
     * @param orderInfo
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result submitSeckillOrder(HttpServletRequest request, @RequestBody OrderInfo orderInfo){
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.valueOf(userId));
        return seckillGoodsService.submitSeckillOrder(orderInfo);
    }


}
